package com.army.study.service;


import com.army.study.common.LogUtils;
import com.army.study.database.CardDB;
import com.army.study.database.DBUtils;
import com.army.study.database.Form;
import com.army.study.utils.ComponentProviderUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentProvider;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.rpc.IRemoteObject;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TimerAbilityService extends Ability {
    private static final String TAG = TimerAbilityService.class.getSimpleName();

    private static final long SEND_PERIOD = 1000L; // 发送周期
    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect = null;

    @Override
    public void onStart(Intent intent) {
        LogUtils.info(TAG,"TimerServiceAbility::onStart");
        if (connect == null) {
            connect = helper.getOrmContext("CardDB", "CardDB.db", CardDB.class);
        }
        startTimer();
        super.onStart(intent);
    }

    /**
     * 卡片更新定时器, 每秒更新一次
     */
    private void startTimer() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateForms();
            }
        }, 0, SEND_PERIOD);
    }

    private void updateForms() {
        // 从数据库中获取卡片信息
        OrmPredicates ormPredicates = new OrmPredicates(Form.class);
        List<Form> formList = connect.query(ormPredicates);
        if (formList.size() < 1) {
            return;
        }
        for (Form form : formList) {
            // 遍历卡片列表更新卡片
            ComponentProvider componentProvider = ComponentProviderUtils.getComponentProvider(form, this);

            Long updateFormId = form.getFormId();
            try {
                updateForm(updateFormId, componentProvider);
            } catch (FormException e) {
                DBUtils.delete(updateFormId,connect);
                LogUtils.error(TAG, "onUpdateForm updateForm error");
            }
        }
    }

    @Override
    public void onBackground() {
        LogUtils.info(TAG,"TimerServiceAbility::onBackground");
        super.onBackground();
    }

    @Override
    public void onStop() {
        LogUtils.info(TAG, "TimerServiceAbility::onStop");
        super.onStop();
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return null;
    }

    @Override
    public void onDisconnect(Intent intent) {
    }
}